package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.Result;
import com.fjh.springboot_01.pojo.tutor.Tutoring;
import com.fjh.springboot_01.pojo.tutor.TutoringBooking;
import com.fjh.springboot_01.service.TutoringService;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tutoring")
public class TutoringController {
    @Autowired
    private TutoringService tutoringService;

    // 发布家教信息
    @PostMapping("/publish")
    public Result<String> publishTutoring(@RequestBody Tutoring tutoring) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以发布家教信息");
        }
        
        tutoring.setTeacherId(userId);
        tutoringService.publishTutoring(tutoring);
        return Result.success("发布成功");
    }

    // 获取所有可用的家教信息
    @GetMapping("/list")
    public Result<List<Tutoring>> getAllTutoring() {
        return Result.success(tutoringService.getAllActiveTutoring());
    }

    // 获取所有可用的家教信息（包含教师认证信息）
    @GetMapping("/list-with-teacher-info")
    public Result<List<Tutoring>> getAllTutoringWithTeacherInfo() {
        return Result.success(tutoringService.getAllActiveTutoringWithTeacherInfo());
    }

    // 获取教师发布的家教信息
    @GetMapping("/teacher")
    public Result<List<Tutoring>> getTeacherTutoring() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以查看此信息");
        }
        
        return Result.success(tutoringService.getTeacherTutoring(userId));
    }

    // 更新家教信息状态
    @PutMapping("/status/{id}")
    public Result<String> updateTutoringStatus(@PathVariable Integer id, @RequestParam Integer status) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以操作");
        }
        
        Tutoring tutoring = tutoringService.getTutoringById(id);
        if (tutoring == null) {
            return Result.error("未找到该家教信息");
        }
        
        if (!tutoring.getTeacherId().equals(userId)) {
            return Result.error("无权操作此家教信息");
        }
        
        tutoringService.updateTutoringStatus(id, status);
        return Result.success("更新成功");
    }

    // 更新家教信息
    @PutMapping("/update")
    public Result<String> updateTutoring(@RequestBody Tutoring tutoring) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以操作");
        }
        
        Tutoring existing = tutoringService.getTutoringById(tutoring.getId());
        if (existing == null) {
            return Result.error("未找到该家教信息");
        }
        
        if (!existing.getTeacherId().equals(userId)) {
            return Result.error("无权操作此家教信息");
        }
        
        tutoring.setTeacherId(userId); // 确保教师ID不被修改
        tutoringService.updateTutoring(tutoring);
        return Result.success("更新成功");
    }

    // 创建预约
    @PostMapping("/booking")
    public Result<String> createBooking(@RequestBody TutoringBooking booking) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以预约家教");
        }
        
        Tutoring tutoring = tutoringService.getTutoringById(booking.getTutoringId());
        if (tutoring == null) {
            return Result.error("未找到该家教信息");
        }
        
        if (tutoring.getStatus() != 1) {
            return Result.error("该家教信息不可预约");
        }
        
        booking.setStudentId(userId);
        booking.setTeacherId(tutoring.getTeacherId());
        
        try {
            tutoringService.createBooking(booking);
            return Result.success("预约成功，等待教师确认");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    // 获取教师收到的预约
    @GetMapping("/booking/teacher")
    public Result<List<TutoringBooking>> getTeacherBookings() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以查看此信息");
        }
        
        return Result.success(tutoringService.getTeacherBookings(userId));
    }

    // 获取学生发出的预约
    @GetMapping("/booking/student")
    public Result<List<TutoringBooking>> getStudentBookings() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以查看此信息");
        }
        
        return Result.success(tutoringService.getStudentBookings(userId));
    }

    // 处理预约（接受/拒绝）
    @PutMapping("/booking/status/{id}")
    public Result<String> handleBooking(@PathVariable Integer id, @RequestParam Integer status) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以操作");
        }
        
        TutoringBooking booking = tutoringService.getBookingById(id);
        if (booking == null) {
            return Result.error("未找到该预约");
        }
        
        if (!booking.getTeacherId().equals(userId)) {
            return Result.error("无权操作此预约");
        }
        
        tutoringService.updateBookingStatus(id, status);
        return Result.success(status == 1 ? "已接受预约" : "已拒绝预约");
    }

    // 获取预约详情
    @GetMapping("/booking/{id}")
    public Result<TutoringBooking> getBookingById(@PathVariable Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        TutoringBooking booking = tutoringService.getBookingById(id);
        if (booking == null) {
            return Result.error("预约不存在");
        }
        
        // 验证权限：只有相关的学生或教师可以查看
        if ((role == 0 && !booking.getStudentId().equals(userId)) || 
            (role == 1 && !booking.getTeacherId().equals(userId))) {
            return Result.error("无权查看此预约");
        }
        
        return Result.success(booking);
    }

    // 获取学生已确认预约的老师的课程
    @GetMapping("/student-confirmed")
    public Result<List<Tutoring>> getStudentConfirmedTutorings() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以查看此信息");
        }
        
        List<Tutoring> tutorings = tutoringService.getStudentConfirmedTutorings(userId);
        
        if (tutorings.isEmpty()) {
            return Result.success(tutorings, "您还没有已确认的预约，请先预约老师并等待确认");
        }
        
        return Result.success(tutorings);
    }

    // 删除已完成的家教预约
    /**
     * 删除家教预约（软删除）
     * 需要在数据库中添加teacher_deleted和student_deleted字段
     * ALTER TABLE tutoring_booking ADD COLUMN teacher_deleted TINYINT(1) DEFAULT 0;
     * ALTER TABLE tutoring_booking ADD COLUMN student_deleted TINYINT(1) DEFAULT 0;
     */
    @DeleteMapping("/booking/{id}")
    public Result<String> deleteBooking(@PathVariable Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        TutoringBooking booking = tutoringService.getBookingById(id);
        if (booking == null) {
            return Result.error("预约不存在");
        }
        
        // 验证权限：只有相关的学生或教师可以删除
        if (role == 0 && !booking.getStudentId().equals(userId)) {
            return Result.error("无权删除此预约");
        } else if (role == 1 && !booking.getTeacherId().equals(userId)) {
            return Result.error("无权删除此预约");
        }
        
        // 只能删除已完成的预约
        if (booking.getStatus() != 3) {
            return Result.error("只能删除已完成的预约");
        }
        
        // 根据角色调用不同的删除方法
        if (role == 1) {
            tutoringService.teacherDeleteBooking(id);
        } else {
            tutoringService.studentDeleteBooking(id);
        }
        
        return Result.success("删除成功");
    }

    /**
     * 管理员获取所有家教信息列表（包括已下架的）
     * @return 所有家教信息
     */
    @GetMapping("/admin/list")
    public Result<List<Tutoring>> adminGetAllTutoring() {
        // 验证是否为管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer role = (Integer) map.get("role");
        
        if (role != 2) {
            return Result.error("只有管理员可以访问");
        }
        
        return Result.success(tutoringService.getAllTutoring());
    }
    
    /**
     * 管理员审核家教信息
     * @param id 家教信息ID
     * @param status 状态（0-下架，1-可用，2-已完成）
     * @return 操作结果
     */
    @PutMapping("/admin/audit/{id}")
    public Result<String> adminAuditTutoring(@PathVariable Integer id, @RequestParam Integer status) {
        // 验证是否为管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer role = (Integer) map.get("role");
        
        if (role != 2) {
            return Result.error("只有管理员可以进行审核");
        }
        
        // 验证状态值是否合法
        if (status < 0 || status > 2) {
            return Result.error("状态值无效");
        }
        
        Tutoring tutoring = tutoringService.getTutoringById(id);
        if (tutoring == null) {
            return Result.error("未找到该家教信息");
        }
        
        try {
            tutoringService.updateTutoringStatus(id, status);
            return Result.success("审核操作成功");
        } catch (Exception e) {
            return Result.error("审核操作失败：" + e.getMessage());
        }
    }
} 